const webpack = require('webpack');
const ifaces = require('os').networkInterfaces();
// 友好错误提示输出
const FriendlyErrorsPlugin = require('@soda/friendly-errors-webpack-plugin');
// const ForkTsCheckerWebpackPlugin = require('fork-ts-checker-webpack-plugin');

const paths = require('./paths');

const ips = Object.keys(ifaces)
  .reduce((result, id) => result.concat(ifaces[id].filter((item) => item.family === 'IPv4')), [])
  .reduce(
    (result, { address }) => {
      if (!result.includes(address)) {
        result.push(address);
      }

      return result;
    },
    ['localhost'],
  );

module.exports = (config) => {
  const port = config.env.PORT || '6677';
  const host = config.appPackageJson.host || '';
  const isUseHost = ![null, undefined, '', 'localhost', '0.0.0.0'].includes(host);
  let devServerConfig = {};
  if (isUseHost) {
    devServerConfig = {
      sockHost: host,
      sockPort: isUseHost ? 443 : port,
    };
  }

  return {
    mode: 'development',
    devtool: 'inline-source-map', // inline-source-map
    output: {
      filename: 'static/js/[name].js',
      chunkFilename: 'static/js/[name].chunk.js',
    },
    devServer: {
      // host,
      // ...devServerConfig,
      historyApiFallback: true, // 单页应用
      compress: true, // gzip 压缩
      port,
      // hot: true, // 开启热模块替换
      // quiet: true,
      // open: true,
      // disableHostCheck: true,
      // clientLogLevel: 'none',
      // watchContentBase: true,
      // overlay: {
      //   errors: true,
      // },
      headers: {
        'Access-Control-Allow-Origin': '*',
        'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE',
      },
      proxy: paths.proxySetup,
    },
    cache: {
      type: 'filesystem', // 缓存方式，filesystem硬盘，memory内存
      allowCollectingMemory: true,
      version: '1.0.0', // 缓存版本号，不同版本不会去对比数据，直接覆盖
    },
    resolve: {
      alias: {
        'react-dom': '@hot-loader/react-dom',
      },
    },
    plugins: [
      new webpack.HotModuleReplacementPlugin(), // 启用 HMR
      new FriendlyErrorsPlugin({
        color: 'green',
        compilationSuccessInfo: {
          messages: [
            'Client available on:',
            ...ips.map((ip) => `http://${ip}:${port}`),
            isUseHost && `https://${host}`,
          ].filter(Boolean),
        },
        onErrors: null,
      }),
      // new ForkTsCheckerWebpackPlugin({
      //   eslint: {
      //     files: './src/**/*.{ts,tsx,js,jsx}', // required - same as command `eslint ./src/**/*.{ts,tsx,js,jsx} --ext .ts,.tsx,.js,.jsx`
      //   },
      // }),
    ],
    performance: {
      hints: false,
    },
  };
};
